package io.zerous.engine

import android.graphics.Bitmap
import android.graphics.Rect
import android.view.SurfaceView

/**
 * Created by Zerous on 2018/2/3.
 */

class RenderView(val game: Game, val framebuffer: Bitmap) : SurfaceView(game), Runnable {
    @Volatile
    var running = false
    lateinit var gameThread: Thread

    fun onResume() {
        running = true
        gameThread = Thread(this)
        gameThread.start()
    }

    fun onPause() {
        running = false
        while (true) {
            gameThread.join()
            break
        }
    }

    override fun run() {
        var dstRect: Rect
        var startTime = System.nanoTime()
        while (running) {
            if (!holder.surface.isValid)
                continue

            val deltaTime = (System.nanoTime() - startTime) / 1000_000_000f
            startTime = System.nanoTime()

            val c = holder.lockCanvas()

            game.currentScreen.update(deltaTime)
            game.currentScreen.render()

            dstRect = c.clipBounds
            c.drawBitmap(framebuffer, null, dstRect, null)

            if (c != null)
                holder.unlockCanvasAndPost(c)
        }
    }
}
